/*
    Copyright: Octavian Marius Chincisan 2012.
    database shortcuts.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include "database.h"
#include "config.h"

using namespace std;

//-----------------------------------------------------------------------------
bool mysqlcls::createtables()
{

    char cwd[128];
    getcwd(cwd,128);
/*
    string un=""; //cin >> un;
    string pw=""; //cin >> pw;
    string sqry = "CREATE USER '";
    sqry += un + "'@'localhost' IDENTIFIED BY '"+pw+"'";

    qry(sqry);

    qry("drop database mitza;");
    qry("create database mitza;");
    qry("commit;");
    qry("use mitza;");

    sqry = "GRANT ALL PRIVILEGES ON *.* TO '";
    sqry += un+"'@'localhost'  WITH GRANT OPTION;";
    qry(sqry.c_str());
    qry("commit;");
*/
    //QryR("source sql/tables.sql;");

    //config._mitza.host.c_str(),config._mitza.user.c_str(),config._mitza.password.c_str()
    string un=GCFG->_mitza.user;
    string pw=GCFG->_mitza.password;

    qry("drop database mitza;");
    qry("create database mitza;");
    qry("commit;");
    qry("use mitza;");

    string sys = "mysql --user=";
    sys += un +" --password="+pw + " mitza < sql/tables.sql";
    system( sys.c_str() );

    qry("use mitza;");
    SR r(qry("SELECT id FROM sess;", true));
    if(r->rows() == 0)
    {
        r.detach();
        qry("INSERT INTO sess (id) values (1);");
    }
    qry("commit;");

    qry("ALTER TABLE wss AUTO_INCREMENT = 1;");
    qry("ALTER TABLE lnks AUTO_INCREMENT = 1;");
    qry("ALTER TABLE kws AUTO_INCREMENT = 1;");
    qry("INSERT INTO config (max_links,max_depth,lnks_perpage) VALUES (512, 3, 8);");

    //disconnect();
    return true;
}

//-----------------------------------------------------------------------------
uint32_t mysqlcls::sess_id()
{
    qry("UPDATE sess SET id=id+1");
    SR r(qry("SELECT id FROM sess;", true));
    return ::atol(r->fetch()[0]);
}







